<?php
session_start();
include_once("../service/receiptService.php");
include_once("../service/productService.php");
include_once("../util/constant.php");
include_once("../util/functionUtil.php");

if(!isset($_SESSION["username"]) || !isset($_SESSION["cart"])) echo "<script>window.location.href = '../index.php';</script>";

$userId = $_SESSION["username"][0];
$code = generateReceiptCode($_SESSION["username"][0]);
$date = date('d/m/Y');
$phoneNumber = $_POST["phoneNumber"];
$deliveryingAddress = $_POST["deliveryingAddress"];
$payingAddress = $_POST["payingAddress"];
$deliveryingDate = $_POST["deliveryingDate"];
$cart = $_SESSION["cart"];

$receiptId = createReceipt($userId, $code, $date, $deliveryingAddress, $payingAddress, $deliveryingDate, $phoneNumber);

foreach($cart as $each){
	$productInfo =  findProductBy($each[0]);
    $discountedPrice = getDiscountedAndOptionalPriceOfProduct($each[0]);
    createReceiptItem($productInfo["PRO_ID"], $receiptId, $discountedPrice * $each[1], $each[1], generateReceiptItemNote($productInfo["DIS_ID"], $productInfo["PRO_ID"]));
    
    foreach($each[2] as $optionItemId){
        createReceiptProductOptionItem($productInfo["PRO_ID"], $receiptId, $optionItemId);
    }
}

function generateReceiptItemNote($disId, $proId){
    $note = "";
    $discount = findDiscountBy($disId);
    if($discount["DIS_NAME"] != "") $note .= "- ".$discount["DIS_NAME"].": ".($discount["DIS_VALUE"] * 100)."%<br/>";
    
    $optionalPriceNotes = findOptionalPriceNoteBy($proId);
    while($row = mysql_fetch_array($optionalPriceNotes)){
        $note .= "- ".$row["NAME"].": ".number_format($row["OPV_VALUE"])."<br/>";    
    }
    return $note;
}

unset($_SESSION["cart"]);
echo "<script>window.location.href = '../profile-cart.php?action=".INSERT_SUCCESSFULLY."#cart-tab';</script>";
?>